package idv.cjcat.pyronova.nodes {
	import flash.display.BitmapData;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import idv.cjcat.pyronova.render.RenderVisitor;
	
	public class TransformableSpriteSheet extends Node {
		
		private var _source:BitmapData;
		public function get source():BitmapData { return _source; }
		public function set source(value:BitmapData):void {
			_source = value;
			_metricDirty = true;
		}
		
		private var _cellWidth:int;
		public function get cellWidth():int { return _cellWidth; }
		public function set cellWidth(value:int):void {
			_cellWidth = (value > 0)?(value):(1);
			_metricDirty = true;
		}
		
		private var _cellHeight:int;
		public function get cellHeight():int { return _cellHeight; }
		public function set cellHeight(value:int):void {
			_cellHeight = (value > 0)?(value):(1);
			_metricDirty = true;
		}
		
		private var _index:int = 0;
		public function get index():int { return _index; }
		public function set index(value:int):void {
			_index = value;
		}
		
		public function TransformableSpriteSheet(source:BitmapData = null, cellWidth:int = 1, cellHeight:int = 1) {
			this.source = source;
			this.cellWidth = cellWidth;
			this.cellHeight = cellHeight;
		}
		
		private var _metricDirty:Boolean = false;
		private var _matrix:Matrix = new Matrix();
		private var _rect:Rectangle = new Rectangle();
		private var _sRect:Rectangle = new Rectangle();
		private var _buffer:BitmapData;
		private var _numCellsX:int;
		private var _numCellsY:int;
		private var _maxIndex:int;
		private var _point:Point = new Point();
		override public function render(visitor:RenderVisitor):void {
			if (source) {
				if (_metricDirty) {
					_numCellsX = int(source.width / _cellWidth);
					_numCellsY = int(source.height / _cellHeight);
					_maxIndex = _numCellsX * _numCellsY;
					_buffer = new BitmapData(_cellWidth, _cellHeight, true, 0x00000000);
					_sRect.width = _cellWidth;
					_sRect.height = _cellHeight;
					
					_metricDirty = false;
				}
				
				var i:int = _index % _maxIndex;
				var indexX:int = i % _numCellsX;
				var indexY:int = int(i / _numCellsX);
				
				_sRect.x = _cellWidth * indexX;
				_sRect.y = _cellHeight * indexY;
				
				_buffer.fillRect(_buffer.rect, 0x00000000);
				_buffer.copyPixels(_source, _sRect, _point);
				
				_matrix.identity();
				_matrix.concat(matrix());
				_matrix.concat(visitor.topMatrix());
				
				visitor.graphics().draw(_buffer, _matrix);
			}
		}
	}
}